package com.douyinkan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.douyinkan.dto.TagDTO;
import com.douyinkan.entity.Tag;
import com.douyinkan.mapper.TagMapper;
import com.douyinkan.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class TagServiceImpl implements TagService {

    @Autowired
    private TagMapper tagMapper;

    @Override
    public List<TagDTO> getAllTags() {
        List<Tag> tags = tagMapper.selectList(null);
        return tags.stream()
                .map(tag -> new TagDTO(tag.getId(), tag.getName()))
                .collect(Collectors.toList());
    }

    @Override
    public TagDTO createTag(String name) {
        // 检查标签是否已存在
        QueryWrapper<Tag> wrapper = new QueryWrapper<>();
        wrapper.eq("name", name);
        Tag existingTag = tagMapper.selectOne(wrapper);
        if (existingTag != null) {
            return new TagDTO(existingTag.getId(), existingTag.getName());
        } else {
            // 如果不存在，创建新标签
            Tag newTag = new Tag(name);
            tagMapper.insert(newTag);
            return new TagDTO(newTag.getId(), newTag.getName());
        }
    }
}